mod my_server;
mod str_utils;
use std::sync::{Arc, Mutex};
mod my_cipher2;
fn main() {
    // println!("{:?}","Helloitsmehellofromtheotherside1".to_string().as_bytes());
    let oringin_key: [u8; 32] = [
        72, 101, 108, 108, 111, 105, 116, 115, 109, 101, 104, 101, 108, 108, 111, 102, 114, 111,
        109, 116, 104, 101, 111, 116, 104, 101, 114, 115, 105, 100, 101, 49,
    ];
    let a = my_cipher2::encrypt("hello,it's me".as_bytes(), &oringin_key);
    println!("{:?}", a);
    let b = my_cipher2::decrypt(&a.unwrap(), &oringin_key);
    println!(" b = {:?}", String::from_utf8(b.unwrap()));
    // print_type_of(&String::from_utf8(b.unwrap()).unwrap());
    let mut connect_count: i8 = 0;
    let mut vec = vec![];
    // let socket_map: HashMap<String, (Socket, Socket)> = HashMap::new();
    // Type::STREAM -> TCP  Type::DGRAM -> UDP
    // 创建一个服务器 ip 为 本地地址，端口为 3170
    let listener = my_server::create_listener(3170);
    println!("server init success！");
    let client_pool = Arc::new(Mutex::new(Vec::new()));
    while connect_count < 2 {
        let (receiver, _) = listener.accept().unwrap();
        let first_msg = my_server::recv_u8(&receiver);
        if String::from_utf8(my_cipher2::decrypt(&first_msg, &oringin_key).unwrap())
            .unwrap()
            .eq("hello,it's me")
        {
            //FIXME 加密随机你那产生
            my_server::send_u8(
                &receiver,
                &my_cipher2::encrypt("11111111111111111111111111111111".as_bytes(), &oringin_key)
                    .unwrap(),
            );
        }
        let local_receiver = receiver.try_clone().unwrap();
        let main_client_pool = client_pool.clone();
        main_client_pool.lock().unwrap().push(local_receiver);
        let my_client_pool = client_pool.clone();
        vec.push(std::thread::spawn(move || {
            my_server::service(receiver, my_client_pool);
        }));
        connect_count += 1;
    }
    while connect_count >= 0 {
        let _ = vec.pop().unwrap().join();
    }
}

// 查看类型
pub fn print_type_of<T>(_: &T) {
    println!("type is {}", std::any::type_name::<T>())
}
